function getSiteCfg() { 
    $.getJSON(
        "/api/tmpo/config_public/",
        function(json){
            var val = 'POC: <a class="POCemail" href="mailto:' +
                      json.tmpo_poc_email + '">' + json.tmpo_poc_name +'</a> '+
                      'Phone: (' + json.tmpo_poc_phone.substr(0,3) + ') ' +
                      json.tmpo_poc_phone.substr(3,3) + '-' + 
                      json.tmpo_poc_phone.substr(6,4);
            $("span.POCemail").append(val); 
        }
    ); 
}

var waitSpan = function(txt, ico) {
    return '<span id="formerrors" class="waitMessage" ' +
           'style="margin: 5px 0px 0px 0px">' + 
           '<img src="/tmpo/images/icons/hourglass.gif" alt="" />' + txt + 
           '</span>';
};

var simpleSpan = function(txt, ico) {
    return '<span id="formerrors" class="waitMessage" ' +
           'style="margin: 5px 0px 0px 0px">' + txt +
           '</span>';
};

var errorSpan = function(txt) {
    return '<span id="formerrors" class="generalErrorMessage" ' +
           'style="margin: 5px 0px 0px 0px">' +
           '<img src="/tmpo/images/icons/error.gif" alt="" />' + txt +
           '</span>';
};

var setMessage = function(msg) {
    $("#formerrors").remove();
    $("#form1").parent().append(msg);
};

var loginSuccess = function(data, textStatus) {
    setMessage(waitSpan('Login successful.  Redirecting.'));
    window.location = $.cookie("tmpoHome") ? $.cookie("tmpoHome") : "/tmpo"+
        "/missions/";
};

var loginError = function(req, status, exc) {
    switch (req.status) {
    case 400:
        setMessage(errorSpan('Login failed. Please try again.'));
        break;
    default:
        setMessage(errorSpan('Server error. Please try again.'));
    }
};

var loginLinkClicked = function() {
    setMessage(waitSpan('New login started...'));
    var user = $("#form1 #username").val();
    var passwd = $("#form1 #password").val();
    jQuery.ajax({
        url:"/api/login/",
        type:"POST",
        data:{"username":user, "password":passwd}, 
        success:loginSuccess, 
        error:loginError
	});
    return false;
};

var loginFormKeyed = function(event) {
    if (event.which == 13) {
        loginLinkClicked();
    }
};

var loginDocReady = function() {
    $("a.loginButton").attr("href", "");
    $("a.loginButton").click(loginLinkClicked);
    $("#form1").keydown(loginFormKeyed);
    var user = $.cookie("auth_user");
    if (user) {
        setMessage(simpleSpan("You're logged out.  Please close your browser "+
            "to clear your credentials."));
        setTimeout(function(){$("#formerrors").fadeOut();}, 10000);
        $("#form1 #username").val(user);
	$("#form1 #password").focus();
    } else {
	$("#form1 #username").focus();
    }
};

$(document).ready(function() {
    getSiteCfg();
    loginDocReady();
});
